import React, {PureComponent} from 'react';
import MyBar from './processBar.js';

const getData = () => {
    return new Promise((resolve) => {
        let result = {
            success: true,
            status: '200',
            msg: '',
            body: {code: '200', msg: '', data: {menuId: new Date().valueOf() + '_menuid'}},
            headers: {},
            error: undefined};
        setTimeout(()=>{
            resolve(result)
        }, 800);
    });
};

export default class RouterMiddleware extends PureComponent{
    constructor(props){
        super(props);

        this.state = {
            menuId: '',
            loaded: false,
            showLoading: false
        };

        this.childrenElement = React.Children.map(props.children, (child)=>{
            return React.cloneElement(child, {
                ...this.props,
                menuId: this.state.menuId
            });
        });
    }
    componentDidMount(){
        this.getPageInfo();
    }

    componentWillReceiveProps(props){
        const preMatch = this.props.match;
        const nextMatch = props.match;
        if(preMatch && nextMatch && preMatch.path !== nextMatch.path){
            this.getPageInfo();
        }
    }

    render() {
        const loaded = this.state.loaded;
        return (
            <>
                <MyBar loading={this.state.showLoading}/>
                {loaded ? this.childrenElement : null}
            </>
        );

    }

    getPageInfo = async () => {
        this.setState({loaded: false, showLoading: true});
        const result = await getData();
        const data = result.body.data;
        this.setState({menuId: data && data.menuId, loaded: true, showLoading: false});
    };
}
